/**
 * 作者: dailc
 * 时间: 2016-05-24
 * 描述: 首页 
 */
define(function(require, exports, module) {
	"use strict";
	//每一个页面都要引入的工具类
	var CommonTools = require('CommonTools_Core');
	//window操作
	var WindowTools = require('WindowTools_Core');
	var StorageTools = require('StorageTools_Core');
	//UI的初始化
	var UITools = require('UITools_Core');
	var GallerySliderTools = require('GallerySliderTools_Core');
	var enumHelper = require('Common_Enum');
	var baseService = require("Base_Service");
	var systemService = require("System_Service");
	var studyLogService = require("StudyLogs_Service");
	var examBookingService = require("ExamBooking_Service");
	//用户数据
	var userInfo;

	//下拉刷新基类
	var pullToRefreshBase;
	//skin-默认为default
	var skin = 'type0';
	//下拉刷新对象
	var pullToRefresh;
	//以下几个是测试加载更多,没有更多数据功能的
	//当前页
	var currpage = 0;
	//每页大小
	var pageSize = 10;

	//每一个页面都要引入的工具类
	// initready 要在所有变量初始化做完毕后
	CommonTools.initReady(initData);
	/**
	 * @description 初始化数据,结合initReady使用
	 * plus情况为plusready
	 * 其它情况为直接初始化
	 */
	function initData(isPlus) {
		//plus下仅支持竖屏显示-设为竖屏,false为横屏
		CommonTools.lockOrientation(true);
		//引入必备文件,下拉刷新依赖于mui
		CommonTools.importFile([
			'js/libs/mui.min.js',
			'js/libs/mui.picker.min.js',
			'js/libs/mustache.min.js'
		], function() {
			userInfo = baseService.getCoach();
			debugger;
			mui('.abc-scrool').scroll({
				deceleration: 0.0005 //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006
			});
			initHomePage(); //初始化页面

			//plus下双击返回退出-需要Mui
			WindowTools.dbClickExit();
			if(isPlus) {
				WindowTools.preloadTemplate();
				//关闭splash
				plus.navigator.closeSplashscreen();
			}
		});
	}

	/*
	 * @description 首页初始化
	 * */
	function initHomePage() {

		initGallerySlider(); //首页轮播图

		var record = document.getElementById("home_record");
		var record1 = document.getElementById('teachRecord');
		coachTeachList(currentDate(), record, record1);
		mui(".mui-scroll").on('tap', '#admin_about', function() {
			WindowTools.createWin(null, '../about/demo_about.html', null, {});
		});
		mui(".mui-grid-9").on('tap', '.mui-table-view-cell', function() {

			var operate = this.getAttribute('operate');
			if(operate == 'locate') {
				WindowTools.createWin(null, './record.html', null, {});
			} else {
				WindowTools.createWin(null, './service_rule.html', null, {});
			}
		});

		//第二页
		initSecond();

		//第三页
		initPullToRefreshBySkin(skin);

		//初始化第三页
		initThreePager();
	}

	function initThreePager() {
		mui('#headPhoto')[0].src = 'http://api.agoshare.com/Register/GetPortrait?imgName=' + userInfo.HeadPortrait + '&type=coach';
		mui('#teacher')[0].innerHTML = '教练:' + userInfo.Name;
		mui('#teacher1')[0].innerHTML = '准驾车型:' + userInfo.CarType + '&nbsp&nbsp科目:' + userInfo.CourseType;
		mui('#teacher2')[0].innerHTML = '地址:' + userInfo.Address;
		//		mui('#teacher3')[0].innerHTML = '';
		mui(".change").on('tap', '#change', function() {
			WindowTools.createWin(null, '../account/change_password.html', null, {});
		});
		
		mui(".change").on('tap', '#exit', function() {
			baseService.clear();
			closeAllPage('../account/login.html');
		});

	}

	function initSecond() {
		document.getElementById('currentDate').innerHTML = currentDate();
		mui(".mui-control-content").on('tap', '#currentDate', function() {
			showPicker();
		});
	}

	function showPicker() {
		var dtPicker = new mui.DtPicker({
			type: "date",
			beginDate: new Date()
		});
		dtPicker.show(function(selectItems) {
			mui("#currentDate")[0].setAttribute("data-exam-time", selectItems.text);
			mui("#currentDate")[0].innerHTML = selectItems.text;
			var record = document.getElementById('teachRecord');
			coachTeachList(selectItems.text, record);
		});
	}

	/**
	 *@description 教练今日教课列表
	 */
	function coachTeachList(date, record, record1) {
		studyLogService.coachTeachList(date, function(res) {
			var fragment = '';
			for(var i = 0; i < res.List.length; i++) {
				var item = res.List[i];
				var operate = '';
				var status = '';
				if(item.Status == 'Waiting') {
					operate = '<button type="button" class="mui-btn mui-btn-yellow mui-pull-right complete" data-id="' + item.StudyLogID + '">完成</button></li>';
				} else {
					status = '<span style="margin-left: 20px;">' + enumHelper.studyLogStatusTypeFormat(item.Status) + '</span>'
				}
				fragment += '<li class="mui-table-view-cell" >' +
					'<p><span>' + item.StudentName + '</span> <span style="margin-left: 20px;">类型:' + item.DrivingLicenseType + '</span>  <span style="margin-left: 20px;">科目:' + item.CourseType + '</span>' + status + '</p>' +
					'<p><span>时段:' + item.Times + '</span> <span style="margin-left: 10px;">时长:' + item.StudyHours + '小时</span> </p>' +
					operate;
			}
			record.innerHTML = '';
			record.innerHTML = fragment;
			
			if(record1 != null) {
				record1.innerHTML = '';
				record1.innerHTML = fragment;
			}
			initRecordListener()
		});
	}
	var tempId;
	var tempcomplete;
	function initRecordListener() {
		mui(".record_list").off("tap", ".complete").on("tap", ".complete", function() {
			
			console.log('aaaaaaa');
			tempId = this.getAttribute("data-id");
			tempcomplete = this;
			mui.confirm("确定要完成吗？",'提示',['取消','确定'], function(e) {
				if(e.index == 1) {
					studyLogService.coachConfirm(tempId, function() {
						tempcomplete.style.display = 'none';
						mui.toast('完成');
					});
				}

			},'div');

		});
	}

	function currentDate() {
		var d = new Date(),
			month = '' + (d.getMonth() + 1),
			day = '' + d.getDate(),
			year = d.getFullYear();

		if(month.length < 2) month = '0' + month;
		if(day.length < 2) day = '0' + day;

		return [year, month, day].join('-');
	}

	/**
	 * @description 初始化图片轮播
	 */
	function initGallerySlider() {
		createGallerySliderDefault();
	}

	/**
	 * @description 创建默认图片轮播
	 */
	function createGallerySliderDefault() {
		//默认轮播数据
		var GalleryData = [{
			id: "testgallery1",
			title: "", //为空
			url: "../../img/banner/1.jpeg"
		}, {
			id: "testgallery2",
			title: "", //为空
			url: "../../img/banner/2.jpeg"
		}, {
			id: "testgallery3",
			title: "", //为空
			url: "../../img/banner/3.jpeg"
		}, {
			id: "testgallery4",
			title: "", //为空
			url: "../../img/banner/4.jpeg"
		}];
		var options = {
			isLoop: true,
			isAuto: true,
			autoTime: 3000,
			//图片的最大高度,可以不传
			maxImgHeight: '100%',
			//如果是每一个item有多张图,那么决定每一行显示几张图
			perLineItem: 2,
			//是否显示下面的Indicator
			isShowIndicator: true,
			//是否显示下面的翻页Indicator
			isShowPageIndicator: false
		};
		addGallery(GalleryData, options);
	}

	/**
	 * @description 添加轮播图片工具方法
	 * @param {JSON} GalleryData
	 * @param {JSON} options 对应参数
	 */
	function addGallery(GalleryData, options) {
		var myGallery = GallerySliderTools.addGalleryLandscape('#gallerySlider', GalleryData, function(e, id) {
			console.log("点击:" + id);
		}, options);
	}

	/**
	 * @description 初始化时通过skin来决定使用哪一种下拉刷新
	 * 注意；初始化下拉刷新请在初始化时使用,重复使用无效
	 * 这里面是异步引入
	 * @param {String} skin
	 */
	function initPullToRefreshBySkin(skin) {
		var generatePullToRefreshCallback = function(targetPullToRefresh) {
			pullToRefreshBase = targetPullToRefresh;
			initPullRefreshList();
		};
		if(skin === 'default') {
			require.async('PullToRefresh_Base_Default_Core', generatePullToRefreshCallback);
		} else if(skin === 'type0') {
			require.async('PullToRefresh_Base_Type0_Core', generatePullToRefreshCallback);
		} else {
			//其它皮肤都需要引入css
			CommonTools.importFile('css/RayApp/RayApp.PullToRefresh.css');
			if(skin === 'type1') {
				require.async('PullToRefresh_Base_Type1_Core', generatePullToRefreshCallback);
			} else if(skin === 'type1_material1') {
				require.async('PullToRefresh_Base_Type1__Material1_Core', generatePullToRefreshCallback);
			} else {
				console.error("错误:传入的下拉刷新皮肤错误,超出范围!");
			}
		}

	}
	/**
	 * @description 测试添加数据
	 * 真实情况添加的数据要根据接口返回数据映射
	 * @param {Number} count 数量
	 * @param {Boolean} isPullDown 是否是下拉刷新
	 */
	function appendData(count, isPullDown) {
		isPullDown = isPullDown || false;
		var fragment = document.createDocumentFragment();
		console.log("page:" + currpage);
		var offset = (currpage - 1) * pageSize;
		var li;
		console.log(offset);
		studyLogService.coachStarList(offset, pageSize, function(retval) {
			for(var i = 0; i < retval.List.length; i++) {
				var item = retval.List[i];
				li = document.createElement('li');
				li.className = 'mui-table-view-cell';
				var date = '';
				if(item.Date != null) {
					date = item.Date.split('T')[0];
				}
				li.innerHTML = '<div style="display: flex;justify-content:space-around">' +
					'<span>' + date + '</span>' +
					'<span>' + item.Times + '</span>' +
					'<span>' + item.Stars + '星</span></div>';

				fragment.appendChild(li);
			}
			var dataContainer = document.getElementById('listdata');
			//添加-下拉刷新时先清除数据
			if(isPullDown) {
				dataContainer.innerHTML = '';
			}
			dataContainer.appendChild(fragment);
			initListeners();
			resetState(isPullDown, retval.List.length);
		}, function() {
			resetState(true, 0);
		});
	}

	/**
	 * @description 监听
	 */
	function initListeners() {
		mui("#listdata").on("tap", "li.mui-table-view-cell", function() {
			var id = this.getAttribute("data-id");
			WindowTools.createWin(null, "evaluate.html", {
				'studyId': id,
			}, {});
		});
	}

	/**
	 * @description 重置状态
	 * @param {Boolean} isPullDown 是否是下拉刷新
	 */
	function resetState(isPullDown, returnDataCount) {
		if(isPullDown) {
			pullToRefresh.endPullDownToRefresh();
			pullToRefresh.refresh();
		} else {
			if(returnDataCount >= pageSize) {
				pullToRefresh.endPullUpToRefresh(false);
			} else {
				pullToRefresh.endPullUpToRefresh(true);
			}
		}
	}

	/**
	 * @description 初始化下拉刷新
	 * 这时候,基类对象已经可以了
	 */
	function initPullRefreshList() {

		var pullUpRefreshCallback = function() {
			var self = this;
			console.log("pull up");
			//当前页++
			currpage++;
			appendData(pageSize, false);
		};
		var pullDownRefreshCallback = function() {
			var self = this;
			console.log("pull down");
			currpage = 1;
			appendData(pageSize, true);

		};
		var element = '#pullrefresh';

		//初始化下拉刷新
		pullToRefresh = pullToRefreshBase.initPullToRefresh({
			//下拉有关
			down: {
				callback: pullDownRefreshCallback,
			},
			//down为null表示不要下拉刷新
			//down: null,
			//上拉有关
			up: {
				//是否自动上拉加载-初始化是是否自动
				auto: true,
				//距离底部高度(到达该高度即触发)
				offset: 100,
				//是否隐藏那个加载更多动画,达到默认加载效果
				show: true,
				callback: pullUpRefreshCallback
			},
			element: element
		});
	}
	
	function closeAllPage(url) {
		var style = {};
		WindowTools.openWinWithTemplate(id, url, null, style);
	}

});